package com.ecarx.module_router;


import com.ecarx.module_router.constant.ModuleServicePath;
import com.ecarx.module_router.service.IProvider;
import com.ecarx.module_router.service.TestService;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 模块间接口交互
 * <p>
 * 示例：
 * <p>
 * 尽可能在调用前初始化，可以选择在 application 初始化
 * DemoService testService = DemoService.getInstance();
 * ModuleServiceManager.get().injection(ModuleServicePath.SERVICE_TEST, testService);
 * <p>
 * 模块中服务实现类
 * public class DemoService implements TestService {
 *
 *     public static class SingletonHelp {
 *         public static DemoService INSTANCE = new DemoService();
 *
 *     }
 *
 *     private DemoService() {
 *
 *     }
 *
 *     public static DemoService getInstance() {
 *         return SingletonHelp.INSTANCE;
 *     }
 *
 *
 *     int testNum = 4;
 *
 *     public int addNum() {
 *         testNum++;
 *         return testNum;
 *     }
 *
 *     @Override
 *     public int getNum() {
 *         return testNum;
 *     }
 * }
 *
 * @Override public int getNum() {
 * return testNum;
 * }
 * }
 * <p>
 * 调用方
 * TestService testService = (TestService) ModuleServiceManager.get().getService(ModuleServicePath.SERVICE_TEST);
 * int num = testService.getNum();
 */
public class ModuleServiceManager {

    public static class SingletonHelp {
        public static ModuleServiceManager INSTANCE = new ModuleServiceManager();

    }

    private ModuleServiceManager() {

    }

    public static ModuleServiceManager get() {
        return SingletonHelp.INSTANCE;
    }

    static Map<ModuleServicePath, IProvider> serviceMap = new ConcurrentHashMap<>();

    public void injection(ModuleServicePath service, IProvider provider) {
        serviceMap.put(service, provider);
    }

    public IProvider getService(ModuleServicePath service) {
        return serviceMap.get(service);
    }

}